package com.dff.jrfw;

import android.app.KeyguardManager;
import android.content.Context;
import android.content.Intent;
import android.hardware.fingerprint.FingerprintManager;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.databinding.DataBindingUtil;

import com.dff.jrfw.common.Constant;
import com.dff.jrfw.databinding.ActivityBiometricIdentifyBinding;
import com.dff.jrfw.model.QueryDeviceInfoModel;
import com.dff.jrfw.remote.CustomCallBack;
import com.dff.jrfw.remote.RetrofitUtils;
import com.dff.jrfw.remote.RetrofitUtilsTwo;
import com.dff.jrfw.requestBody.BindDeviceDto;
import com.dff.jrfw.utils.DeviceIdUtil;
import com.dff.jrfw.utils.GsonUtils;
import com.dff.jrfw.utils.SharedPreferenceUtils;
import com.dff.jrfw.utils.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;

public class BiometricIdentifyActivity extends BaseActivity implements View.OnClickListener {

    private ActivityBiometricIdentifyBinding binding;
    private String curLoginAccount;
    private String useStatus = "0";


    public static void callMe(Context context) {
        Intent intent = new Intent(context, BiometricIdentifyActivity.class);
        context.startActivity(intent);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_biometric_identify);
        initView();
    }

    private void initView() {
        binding.ivBack.setOnClickListener(this);
        binding.ivFinger.setOnClickListener(this);
        if (supportFingerprint()) {
            curLoginAccount = (String) SharedPreferenceUtils.getInstance().get(BiometricIdentifyActivity.this, Constant.CURRENT_LOGIN_ACCOUNT, "");
            queryDeviceInfo(curLoginAccount);
        } else {
            useStatus = "0";
            binding.ivFinger.setImageResource(R.drawable.ic_switch_off);
            binding.ivFinger.setClickable(true);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_finger:
                if (useStatus.equals("0")) {
                    if (supportFingerprint()) {
                        bindDevice();
                    }
                } else {
                    deBindDevice();
                }
                break;
        }

    }

    // 是否支持指纹
    private boolean supportFingerprint() {
        if (Build.VERSION.SDK_INT < 23) {
            ToastUtil.toast("您的系统版本过低，不支持指纹功能");
            return false;
        } else {
            KeyguardManager keyguardManager = getSystemService(KeyguardManager.class);

            FingerprintManager fingerprintManager = getSystemService(FingerprintManager.class);
            if (fingerprintManager != null) {
                if (!fingerprintManager.isHardwareDetected()) {
                    ToastUtil.toast("您的手机不支持指纹功能");
                    return false;
                } else if (keyguardManager != null) {
                    if (!keyguardManager.isKeyguardSecure()) {
                        ToastUtil.toast("您还未设置锁屏，请先设置锁屏并添加一个指纹");
                        return false;
                    } else if (!fingerprintManager.hasEnrolledFingerprints()) {
                        ToastUtil.toast("您至少需要在系统设置中添加一个指纹");
                        return false;
                    }
                } else {
                    ToastUtil.toast("键盘管理初始化失败");
                    return false;
                }
            } else {
                ToastUtil.toast("指纹管理初始化失败");
                return false;
            }
        }
        return true;
    }


    private void queryDeviceInfo(String username) {
        showLoading();
        RetrofitUtilsTwo.getService().doAccountIsAlive("1", "1", username).enqueue(new CustomCallBack<ResponseBody>() {

            @Override
            public void onFailure(Call call, Throwable t) {
                super.onFailure(call, t);
                hideLoading();
            }

            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                hideLoading();
                try {
                    if (response.body() != null) {
                        String result = response.body().string();
                        JSONObject jsonObject = new JSONObject(result);
                        int code = jsonObject.getInt("code");
                        if (code == 200) {
                            JSONObject data = jsonObject.optJSONObject("data");
                            String muDevices = data.optString("muDevices");
                            if (!"null".equals(muDevices) && !TextUtils.isEmpty(muDevices)) {
                                List<QueryDeviceInfoModel.MuDevicesDTO> muDevicesDTOS = GsonUtils.jsonToList(muDevices, QueryDeviceInfoModel.MuDevicesDTO.class);
                                String deviceId = DeviceIdUtil.getDeviceId(BiometricIdentifyActivity.this);
                                for (int i = 0; i < muDevicesDTOS.size(); i++) {
                                    if (muDevicesDTOS.get(i).getDeviceId().equals(deviceId)) {
                                        if (muDevicesDTOS.get(i).getFpSwitch() == 1) {         //指纹开关启用
                                            useStatus = "1";
                                            binding.ivFinger.setImageDrawable(getResources().getDrawable(R.drawable.ic_switch_on));
                                        } else {
                                            useStatus = "0";
                                            binding.ivFinger.setImageDrawable(getResources().getDrawable(R.drawable.ic_switch_off));
                                        }
                                        return;
                                    }
                                }
                                useStatus = "0";
                                binding.ivFinger.setImageDrawable(getResources().getDrawable(R.drawable.ic_switch_off));
                            } else {
                                useStatus = "0";
                                binding.ivFinger.setImageDrawable(getResources().getDrawable(R.drawable.ic_switch_off));
                            }
                            binding.ivFinger.setClickable(true);
                        } else {
                            String msg = jsonObject.getString("msg");
                            ToastUtil.toast(msg);
                        }
                    } else {
                        ResponseBody errorResponseBody = response.errorBody();
                        if (errorResponseBody != null) {
                            ToastUtil.toast(errorResponseBody.string());
                        }
                    }
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    private void bindDevice() {
        showLoading();
        BindDeviceDto bindDeviceDto = new BindDeviceDto();
        String deviceId = DeviceIdUtil.getDeviceId(BiometricIdentifyActivity.this);
        bindDeviceDto.setDeviceId(deviceId);
        bindDeviceDto.setUno(curLoginAccount);
        bindDeviceDto.setFpSwitch(1);
        RetrofitUtils.getService().bindDevice("1", "1", bindDeviceDto).enqueue(new CustomCallBack<ResponseBody>() {
            @Override
            public void onFailure(Call call, Throwable t) {
                super.onFailure(call, t);
                hideLoading();
            }

            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                hideLoading();
                try {
                    if (response.body() != null) {
                        String result = response.body().string();
                        JSONObject jsonObject = new JSONObject(result);
                        int code = jsonObject.getInt("code");
                        if (code == 200) {
                            useStatus = "1";
                            binding.ivFinger.setImageDrawable(getResources().getDrawable(R.drawable.ic_switch_on));
                            ToastUtil.toast("开启指纹识别成功");
                        } else {
                            String msg = jsonObject.getString("msg");
                            ToastUtil.toast(msg);
                        }
                    } else {
                        ResponseBody errorResponseBody = response.errorBody();
                        if (errorResponseBody != null) {
                            ToastUtil.toast(errorResponseBody.string());
                        }
                    }
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    private void deBindDevice() {
        showLoading();
        BindDeviceDto bindDeviceDto = new BindDeviceDto();
        String deviceId = DeviceIdUtil.getDeviceId(BiometricIdentifyActivity.this);
        bindDeviceDto.setDeviceId(deviceId);
        bindDeviceDto.setUno(curLoginAccount);
        bindDeviceDto.setFpSwitch(0);
        RetrofitUtils.getService().bindDevice("1", "1", bindDeviceDto).enqueue(new CustomCallBack<ResponseBody>() {

            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                hideLoading();
                try {
                    if (response.body() != null) {
                        String result = response.body().string();
                        JSONObject jsonObject = new JSONObject(result);
                        int code = jsonObject.getInt("code");
                        if (code == 200) {
                            useStatus = "0";
                            binding.ivFinger.setImageDrawable(getResources().getDrawable(R.drawable.ic_switch_off));
                            ToastUtil.toast("关闭指纹识别成功");
                        } else {
                            String msg = jsonObject.getString("msg");
                            ToastUtil.toast(msg);
                        }
                    } else {
                        ResponseBody errorResponseBody = response.errorBody();
                        if (errorResponseBody != null) {
                            ToastUtil.toast(errorResponseBody.string());
                        }
                    }
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call call, Throwable t) {
                super.onFailure(call, t);
                hideLoading();
            }
        });


//        String deviceId = DeviceIdUtil.getDeviceId(BiometricIdentifyActivity.this);
//        RetrofitUtils.getService().deBindDevice("1", "1", deviceId, curLoginAccount).enqueue(new CustomCallBack<ResponseBody>() {
//            @Override
//            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
//                try {
//                    if (response.body() != null) {
//                        String result = response.body().string();
//                        JSONObject jsonObject = new JSONObject(result);
//                        int code = jsonObject.getInt("code");
//                        if (code == 200) {
//                            useStatus = "0";
//                            binding.ivFinger.setImageDrawable(getResources().getDrawable(R.drawable.ic_switch_normal));
//                            ToastUtil.toast("关闭指纹识别成功");
//                        } else {
//                            String msg = jsonObject.getString("msg");
//                            ToastUtil.toast(msg);
//                        }
//                    } else {
//                        ResponseBody errorResponseBody = response.errorBody();
//                        if (errorResponseBody != null) {
//                            ToastUtil.toast(errorResponseBody.string());
//                        }
//                    }
//                } catch (IOException | JSONException e) {
//                    e.printStackTrace();
//                }
//            }
//        });
    }


}